package com.anjoyo.xgh.musicshare.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.anjoyo.musicshare.activity.customui.lyrc.Lyric;
import com.anjoyo.musicshare.activity.customui.lyrc.LyricView;
import com.anjoyo.musicshare.activity.customui.lyrc.PlayListItems;
import com.anjoyo.xgh.musicshare.R;
import com.anjoyo.xgh.musicshare.adapter.MyPagerAdapter;
import com.anjoyo.xgh.musicshare.adapter.NowListAdapter;
import com.anjoyo.xgh.musicshare.api.CollectApi;
import com.anjoyo.xgh.musicshare.application.SongApplication;
import com.anjoyo.xgh.musicshare.entry.Song;
import com.anjoyo.xgh.musicshare.util.BitmapUtil;
import com.anjoyo.xgh.musicshare.util.Constant;
import com.anjoyo.xgh.musicshare.util.Constant.PLAYSTATUS;
import com.anjoyo.xgh.musicshare.util.StringUtil;

public class PlayAct extends Activity implements OnClickListener {
	ImageView ivplay, ivbackground, ivlike;
	TextView tvsongname, tvsongtime, tvsongnowtime;
	SeekBar songBar;
	ViewPager viewPager;
	LayoutInflater inflater;
	int duration = 9999999;
	Song song;
	NowMusicReciver reciver;
	NowMusicThread mythread;
	int nowtime;
	NowListAdapter dAdapter;
	LyricView lrcView;
	String filepath;
	String imgurl;
	Context con;
	boolean b1 = true;
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				tvsongnowtime.setText(StringUtil.turnTime(nowtime));
				songBar.setProgress(nowtime * 100 / duration);
				if (b1) {
					duration = SongApplication.getInstance().player
							.getDuration();
					System.out.println("duration的值" + duration);
					tvsongtime.setText(StringUtil.turnTime(duration));
					b1 = false;
				}
				try {
					lrcView.updateIndex(nowtime, null);
					lrcView.setinvalidate();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (msg.what == Constant.DOWLOAD_OK) {
				Toast.makeText(con, "图片加载成功", 0).show();
				File file = new File(filepath);
				if (file.length() > 5) {
					ivbackground.setImageURI(Uri.parse(filepath));
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play_layout);
		con = this;
		reciver = new NowMusicReciver();
		IntentFilter inf = new IntentFilter();
		inf.addAction(Constant.ACTION_UPDATE_MUSIC);
		inf.addAction(Constant.ACTION_UPDATE_TIME);
		this.registerReceiver(reciver, inf);
		mythread = new NowMusicThread();
		mythread.start();

		ivlike = (ImageView) findViewById(R.id.iv_like);
		findViewById(R.id.iv_ago).setOnClickListener(this);
		findViewById(R.id.iv_play).setOnClickListener(this);
		findViewById(R.id.iv_next).setOnClickListener(this);
		ivplay = (ImageView) findViewById(R.id.iv_play);
		tvsongname = (TextView) findViewById(R.id.tv_songname);
		tvsongtime = (TextView) findViewById(R.id.tv_songtime);
		tvsongnowtime = (TextView) findViewById(R.id.tv_songnowtime);
		songBar = (SeekBar) findViewById(R.id.sb_song);

		init();
		update();
		songBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				SongApplication.getInstance().player.seekTo(seekBar
						.getProgress() * duration / 100);
				SongApplication.getInstance().player.start();
				ivplay.setImageResource(R.drawable.pa_pause);
				SongApplication.status = PLAYSTATUS.PLAYING;
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				SongApplication.getInstance().player.pause();
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
			}
		});
		findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		ivlike.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (song!=null) {
					if (song.isIsnetMusic()) {
						CollectApi api = new CollectApi();
						api.clodesong(con, song);
					} else {
						long i = SongApplication.getInstance().getDBhelper()
								.saveMusic(song, true, false);
						if (i != 0) {
							Toast.makeText(con, "收藏成功", 0).show();
						} else {
							Toast.makeText(con, "已收藏过", 0).show();
						}
					}
					ivlike.setImageResource(R.drawable.feed_liked);
				}else {
					Toast.makeText(con, "请选择音乐……", 0).show();
				}
			}
		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(reciver);
	}

	public void init() {

		/*---------------------------------设置滑动页面---------------------------------*/
		viewPager = (ViewPager) findViewById(R.id.pager);
		ivbackground = (ImageView) findViewById(R.id.iv_songbg);
		inflater = LayoutInflater.from(this);

		List<View> views = new ArrayList<View>();
		View v1 = inflater.inflate(R.layout.lrc_layout, null);
		View v2 = inflater.inflate(R.layout.nowlist_layout, null);
		ListView listView = (ListView) v2.findViewById(R.id.nowlist);

		dAdapter = new NowListAdapter(this,
				SongApplication.getInstance().currentlist);
		listView.setAdapter(dAdapter);
		lrcView = (LyricView) v1.findViewById(R.id.lrcView);
		views.add(v1);
		views.add(v2);
		MyPagerAdapter adapter = new MyPagerAdapter(views);
		viewPager.setAdapter(adapter);
		viewPager.setCurrentItem(views.size()*100+2);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				dAdapter.changeColor(arg2);
				Intent intent = new Intent(Constant.ACTION_PLAY);
				intent.putExtra("pos", arg2);
				sendBroadcast(intent);
			}
		});
		/*---------------------------------设置滑动页面---------------------------------*/
	}

	// 加载歌曲背景图片
	public void showImg(Song song) {
		// ivbackground.setImageURI(Uri.parse(Constant.CACHE + "b1.jpg"));
		ivbackground.setImageResource(R.drawable.bg);
		if (song.isIsnetMusic()) {
			// imgurl转码后的歌手图片url
			String img = StringUtil.zhuanma(song.getImage_url());
			imgurl = Constant.SINGER_URL + img + ".jpg";

			filepath = Constant.SINGER_IMG + song.getImage_url() + ".jpg";
			if (!StringUtil.isnull(img)) {
				File imFile = new File(filepath);
				if (imFile.exists() && imFile.length() > 10) {
					ivbackground.setImageURI(Uri.parse(filepath));
				} else {
					new BitmapUtil().saveNetImg(imgurl, filepath, handler);
				}
			}
		} else {
			if (!StringUtil.isnull(song.getArtist())) {
				filepath = Constant.SINGER_IMG + song.getArtist() + ".jpg";
				File imFile = new File(filepath);
				if (imFile.exists() && imFile.length() > 10) {
					ivbackground.setImageURI(Uri.parse(filepath));
				}
			}
		}
	}

	// 显示歌词
	public void showlrc(Song song) {
		// if (!StringUtil.isnull(song.getArtist())
		// && !song.getArtist().equals("<unknown>")) {
		String lrcurl = Constant.SERVER_IP
				+ "/lrc/"
				+ StringUtil.pasekongge(song.getArtist() + "-" + song.getName()
						+ ".lrc");

		PlayListItems items = new PlayListItems(Constant.LRC_PATH,
				song.getName(), song.getArtist(), StringUtil.pasekongge(lrcurl));
		Lyric lrc = new Lyric(items);
		lrcView.setmLyric(lrc);
		lrcView.setSentencelist(lrc.list);
		lrcView.setCurrentPaintColor(Color.BLUE);
		lrcView.setNotCurrentPaintColor(Color.WHITE);
		lrcView.setCurrentTextSize(100);
		lrcView.setTextSize(80);
		lrcView.setTexttypeface(Typeface.SERIF);
		lrcView.setTextHeight(40);
		// }
	}

	public void update() {
		song = SongApplication.currentsong;
		if (song!=null) {
			showlrc(song);
			showImg(song);
			// duration = SongApplication.getInstance().player.getDuration();
			// System.out.println("duration的值"+duration);
			tvsongname.setText(song.getName() + "-" + song.getArtist());
			// tvsongtime.setText(StringUtil.turnTime(duration));
			int i = SongApplication.getInstance().getDBhelper()
					.isfav(song);
			if (i > 0) {
				ivlike.setImageResource(R.drawable.feed_liked);
			} else {
				ivlike.setImageResource(R.drawable.feed_unlike);
			}
			dAdapter.changeColor(SongApplication.currentpos);
			b1 = true;
		}else {
			ivbackground.setImageResource(R.drawable.bg);
			tvsongname.setText("");
		}
		
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.iv_ago:
			ivplay.setImageResource(R.drawable.pa_pause);
			intent.setAction(Constant.ACTION_AGO);
			break;
		case R.id.iv_play:
			if (song!=null) {
				intent.setAction(Constant.ACTION_PLAY);
				if (SongApplication.status == PLAYSTATUS.WAITE) {
					ivplay.setImageResource(R.drawable.pa_pause);
				} else if (SongApplication.status == PLAYSTATUS.PLAYING) {
					ivplay.setImageResource(R.drawable.pa_play);
				} else if (SongApplication.status == PLAYSTATUS.PAUSE) {
					ivplay.setImageResource(R.drawable.pa_pause);
				}
			}else {
				Toast.makeText(con, "请选择音乐……", 0).show();
			}
			break;
		case R.id.iv_next:
			ivplay.setImageResource(R.drawable.pa_pause);
			intent.setAction(Constant.ACTION_NEXT);
			break;
		default:
			break;
		}
		sendBroadcast(intent);
	}

	class NowMusicReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constant.ACTION_UPDATE_MUSIC)) {
				update();
			}
			if (action.equals(Constant.ACTION_UPDATE_TIME)) {

			}
		}
	}

	boolean ischange = false;

	class NowMusicThread extends Thread {
		@Override
		public void run() {
			while (true) {
				while (SongApplication.getInstance().player.isPlaying()) {
					nowtime = SongApplication.getInstance().player
							.getCurrentPosition();
					handler.sendEmptyMessage(1);
					// System.out.println("send:handler");
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
